import CryptoJS from 'crypto-js'
import moment from 'moment'
import router from '@/router'

// 随机生成指定数量的16进制key
export const generatekey = (num) => {
  let library = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let key = ''
  for (let i = 0; i < num; i++) {
    let randomPoz = Math.floor(Math.random() * library.length)
    key += library.substring(randomPoz, randomPoz + 1)
  }
  return key
}

// 加密
export const encrypt = (word, keyStr) => {
  keyStr = keyStr ? keyStr : 'abcdsxyzhkj12345'
  let key = CryptoJS.enc.Utf8.parse(keyStr)
  let srcs = CryptoJS.enc.Utf8.parse(word)
  let encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.toString()
}

// 解密
export const decrypt = (word, keyStr) => {
  keyStr = keyStr ? keyStr : 'abcdsxyzhkj12345'
  let key = CryptoJS.enc.Utf8.parse(keyStr)
  let decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}

// 日期格式化
export const dateFormat = (timestamp, type = 1) => {
  if (!timestamp) return

  const obj = {
    1: 'YYYY-MM-DD HH:mm:ss',
    2: 'YYYY-MM-DD HH:mm',
    3: 'YYYY-MM-DD',
    4: 'YYYY'
  }

  if (String(timestamp).length === 10) return moment.unix(parseInt(timestamp)).format(obj[type])
  if (String(timestamp).length === 13) return moment(parseInt(timestamp)).format(obj[type])
}

// 数字 千分位分隔符
export const amountFormat = (number) => {
  if (number === null || number === undefined) return
  let n = number
  let r = ''
  let temp = ''
  do {
    // 求模的值， 用于获取高三位，这里可能有小数
    let mod = n % 1000
    // 值是不是大于1，是继续的条件
    n = n / 1000
    // 高三位
    temp = ~~mod
    // 1.填充: n > 1 循环未结束， 就要填充为比如 1 => 001
    // 不然temp = ~~mod的时候, 1 001， 就会变成 "11"
    // 2.拼接“,”
    r = (n >= 1 ? `${temp}`.padStart(3, '0') : temp) + (!!r ? ',' + r : '')
  } while (n >= 1)
  const strNumber = number + ''
  let index = strNumber.indexOf('.')
  // 拼接小数部分
  if (index >= 0) {
    r += strNumber.substring(index)
  }
  return r
}

// 去除html标签 指定长度
export const toText = (str, len) => {
  if(!str) return ''
  const re1 = new RegExp('<.+?>|&.+?;', 'g') //匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
  let msg = str.replace(re1, '') //执行替换成空字符
  //msg = msg.replace(/\s/g, '') //去掉所有的空格（中文空格、英文空格都会被替换）
  msg = msg.replace(/[\r\n]/g, '') //去掉所有的换行符
  return msg?.replace(/<[^>]+>/g, '').substring(0, len)
}

// 设置项目编号
export const setItemNumber = (data) => {
  if (!Array.isArray(data)) return

  // 一级编号
  const level1Arr = []
  for (let index = 0; index < 26; index++) {
    const s = String.fromCharCode(index + 65)
    if (['I'].includes(s)) continue
    level1Arr.push(s)
  }

  let i1 = 0
  let i2 = 0
  let i3 = 0
  let i4 = 0
  let i5 = 0
  const level2Arr = [] // 二级编号
  const level3Arr = [] // 三级编号
  const level4Arr = [] // 四级编号
  const level5Arr = [] // 五级编号
  data.forEach((item) => {
    if (item.dataType === '1') {
      item.itemNumber = '--'
      return
    }
    let itemNumber = ''

    // 一级
    if (item.projectLevel === 0) {
      itemNumber += level1Arr[i1]
      level2Arr.push(itemNumber)
      i1++
      i2 = 0
    }

    // 二级
    if (item.projectLevel === 1) {
      i2++
      i3 = 0
      let num = i2
      // if (num.toString().length < 2) {
      //   num = `0${num}`
      // }
      itemNumber += `${level2Arr[level2Arr.length - 1]}-${num}`
      level3Arr.push(itemNumber)
    }

    // 三级
    if (item.projectLevel === 2) {
      i3++
      i4 = 0
      let num = i3
      if (num.toString().length < 2) {
        num = `0${num}`
      }
      itemNumber += `${level3Arr[level3Arr.length - 1]}-${num}`
    }

    // 四级
    if (item.projectLevel === 3) {
      i4++
      i5 = 0
      itemNumber = i4
      level5Arr.push(itemNumber)
    }

    // 五级
    if (item.projectLevel === 4) {
      i5++
      let num = i5
      itemNumber += `${level5Arr[level5Arr.length - 1]}-${num}`
    }

    item.itemNumber = itemNumber
  })
}

// 下载
export const download = (data) => {
  const blob = data
  const reader = new FileReader()
  reader.readAsDataURL(blob)
  reader.onload = (e) => {
    const a = document.createElement('a')
    a.download = window.fileName || ''
    a.href = e.target.result
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.fileName = null
  }
}

// 随机颜色
export const getRandomColor = function (a = 0.1) {
  let r = Math.floor(Math.random() * 256)
  let g = Math.floor(Math.random() * 256)
  let b = Math.floor(Math.random() * 256)
  return `rgba(${r},${g},${b}, ${a})`
}

// 新窗口打开
export const openUrl = (path, query) => {
  const url = router.resolve({
    path,
    query
  })
  window.open(url.href)
}
